<?php
class LoginController extends Zend_Controller_Action
{
	public function init(){
		//set layout
        $layoutPath = APPLICATION_PATH . '/templates/default/login';
        $option = array('layout' => 'index', 'layoutPath' => $layoutPath);
        Zend_Layout::startMvc($option);
	}
	
    public function indexAction ()
    {
        Zend_Loader::loadClass("AuthModel");
        Zend_Loader::loadClass("LogModel");
        Zend_Loader::loadClass("LogLine");
        $logModel = new LogModel();
        $logLine = $logModel->getLogLine();

        $request = $this->getRequest();
        $view = $this->view;
        
        $auth = new AuthModel();
        
        //TODO ユーザがログインした場合
        if($auth->isLoggedIn()){
        	if($auth->getUserInfo("type")== ADMIN_USER){
        		$this->_redirect("/admin/index");
        	}else{
        		$this->_redirect("/user/index");
        	}
        }
        
        if($request->isPost()){
	        $auth = new AuthModel();
	        
	        $user = $request->getParam("login");
	        $pass = $request->getParam("pass");
	        
	        if($auth->login($user, $pass)){
	        	$logLine->setType(LogLine::TYPE_OPERATION);
	        	$logLine->addParts($user);
	        	$logLine->addParts($pass);
	        	$logLine->setTime();
	        	$logModel->addLogLine($logLine);
	        	$logModel->flush();
				
	        	if($auth->getUserInfo("type")== ADMIN_USER){
	        		$this->_redirect("/admin/index");
	        	}else{
	        		$this->_redirect("/user/index");
	        	}
	        	
	        }else{
	        	//ログインエラー
	        	$err_msg = "ユーザ名とパスワードが違う";
	        	$err_msg = "ユーザ名とかパスワードが間違っています";

	        	$logLine->setType(LogLine::TYPE_ERROR);
	        	$logLine->addParts($user);
	        	$logLine->addParts($pass);
	        	$logLine->setTime();
	        	$logModel->addLogLine($logLine);
	        	$logModel->flush();
	
	        	$view->err_msg = $err_msg;
	        }    
        }
		
    }
    
    public function logoutAction(){
    	Zend_Loader::loadClass("AuthModel");
    	
    	$auth = new AuthModel();
    	$auth->logout();
    	
    	$this->_redirect("/login");
    }
}